const OFFSET = 150

const animateMap = new WeakMap()
const ob = new IntersectionObserver((entries) => {
  for (const entrie of entries) {
    if (entrie.isIntersecting) {
      const animation = animateMap.get(entrie.target)
      animation?.play()
      ob.unobserve(entrie.target)
    }
  }
})

function isBelowViewport(el: HTMLElement): boolean {
  const rect = el.getBoundingClientRect()
  return rect.top > window.innerHeight
}

export default {
  mounted(el: HTMLElement) {
    if (!isBelowViewport(el)) return
    const animation = el.animate(
      [
        {
          transform: `translateY(${OFFSET}px)`,
          opacity: 0.5
        },
        {
          transform: `translateY(0)`,
          opacity: 1
        }
      ],
      {
        duration: 1000,
        easing: 'ease'
      }
    )
    animation.pause()
    animateMap.set(el, animation)
    ob.observe(el)
  },
  unmounted(el: HTMLElement) {
    ob.unobserve(el)
  }
}
